package com.atjava.nebula.web.jbpm;

import java.io.File;
import java.io.FilenameFilter;
import java.util.HashMap;

import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.internal.io.ResourceFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Assert;

import com.atjava.nebula.core.exception.baseExp.SystemException;

public class JbpmProcessConfiguration {
	
	private String processLocation;
	
	private HashMap<Resource, ResourceType> processMap = 
			new HashMap<Resource, ResourceType>();

	public void init(){
		//String jbpmLocation = sce.getServletContext().getInitParameter("jbpmLocation");
		String jbpmFolderPath = "";
		String jbpmFolderName = "";
		try {
			Assert.isTrue(processLocation.startsWith("classpath:"));
			int index = processLocation.indexOf(":");
			jbpmFolderName = processLocation.substring(index+1);
			jbpmFolderPath = new ClassPathResource(jbpmFolderName).getFile().getAbsolutePath();
		} catch (Exception e) {
			throw new SystemException("Init jbpm process error, folder path ["+processLocation+"].");
		}
		
		File processFolder = new File(jbpmFolderPath);
		
		if(!processFolder.isDirectory()){
			throw new SystemException("Jbpm process folder path is not a directory ["+jbpmFolderPath+"].");
		}
		
		String [] processFiles = processFolder.list(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				if(name.endsWith(".bpmn"))
					return true;
				return false;
			}
		});
		
		for (int i = 0; i < processFiles.length; i++) {
			Resource processResource = 
					ResourceFactory.newClassPathResource(jbpmFolderName + File.separator + processFiles[i]);
			processMap.put(processResource, ResourceType.BPMN2);
		}
	}

	public void setProcessLocation(String processLocation) {
		this.processLocation = processLocation;
	}

	public HashMap<Resource, ResourceType> getProcessMap() {
		return processMap;
	}
	
}
